extends NodeState

@export var zombie: Zombie

var death_animation_finished: bool = false
var death_timer: float             = 0.0
var death_duration: float          = 3.0  # 死亡动画持续时间


func _on_enter() -> void:
	print("僵尸进入死亡状态")

	if zombie:
		# 停止所有移动
		zombie.velocity = Vector2.ZERO
		zombie.is_dead = true

		# 播放死亡动画（随机选择两个死亡动画之一）
		var death_animations: Array[Variant] = ["death_1"]
		var random_death                     = death_animations[0]
		zombie.animated_sprite.play(random_death)

		# 连接动画完成信号
		if not zombie.animated_sprite.animation_finished.is_connected(_on_death_animation_finished):
			zombie.animated_sprite.animation_finished.connect(_on_death_animation_finished)

		# 禁用碰撞
		zombie.set_collision_layer_value(4, false)  # 禁用敌人碰撞层
		zombie.set_collision_mask_value(1, false)   # 禁用与玩家的碰撞检测

		# 禁用受伤组件
		if zombie.hurt_component:
			zombie.hurt_component.set_collision_layer_value(4, false)
			zombie.hurt_component.set_collision_mask_value(3, false)


func _on_physics_process(delta: float) -> void:
	if death_animation_finished:
		death_timer += delta

		# 死亡动画播放完成后，开始淡出效果
		if death_timer < death_duration:
			var fade_progress: float = death_timer / death_duration
			var alpha: float         = 1.0 - fade_progress
			zombie.animated_sprite.modulate.a = alpha
		else:
			# 完全淡出后销毁僵尸
			zombie.queue_free()


func _on_death_animation_finished():
	death_animation_finished = true
	print("死亡动画播放完成")


func _on_next_transitions() -> void:
	# 死亡状态不需要转换到其他状态
	pass


func _on_exit() -> void:
	# 断开动画信号连接
	if zombie and zombie.animated_sprite.animation_finished.is_connected(_on_death_animation_finished):
		zombie.animated_sprite.animation_finished.disconnect(_on_death_animation_finished)
